import React, { Component } from 'react';
import Head from './components/head';
import Book from './components/book';
import './App.css';
import pubsub from 'pubsub-js'

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bookList: [
        { id: 1, src: 'https://img.alicdn.com/bao/uploaded/i3/445406692/O1CN01cTLltl1zIzBtxjuVO_!!0-item_pic.jpg_130x130.jpg', title: '道德经', sales: 10, isShow: true },
        { id: 2, src: 'https://img.alicdn.com/bao/uploaded/i3/445406692/O1CN01kMVRKP1zIzBrBNiX0_!!0-item_pic.jpg_130x130.jpg', title: '史记', sales: 990, isShow: true },
        { id: 3, src: 'https://img.alicdn.com/bao/uploaded/i1/2293797464/O1CN01BSXPhI250YopLx33u_!!0-item_pic.jpg_130x130.jpg', title: '人家告白', sales: 120, isShow: true },
        { id: 4, src: 'https://img.alicdn.com/bao/uploaded/i1/2293797464/O1CN01nLoh5G250Yosy0TiQ_!!0-item_pic.jpg_130x130.jpg', title: '罗生门', sales: 100, isShow: true }
      ]
    }
  }
  componentDidMount () {
    // 事件发布订阅：https://www.jianshu.com/p/c357707a2c96
    pubsub.subscribe('search', (_, val) => {
      const data = [...this.state.bookList];
      data.forEach((item) => {
        if (item.title.indexOf(val) !== -1) {
          item.isShow = true
        } else {
          item.isShow = false
        }
      })
      this.setState({
        bookList: data
      })
    });
    pubsub.subscribe('sort', () => {
      const data = [...this.state.bookList];
      data.sort((a,b)=>{
        return b.sales - a.sales
      })
      this.setState({
        bookList: data
      })
    });
  }
  render (h) {
    return (
      <div className='home'>
        <Head search={this.search} />
        <div className='book_content'>
          {
            this.state.bookList.map((item) => (
              item.isShow && <Book key={item.id} src={item.src} title={item.title} sales={item.sales} />
            ))
          }
        </div>
      </div>
    )
  }
}

export default App;